import { forwardRef, useImperativeHandle, useState } from 'react';

import { useRequest } from 'ahooks';
import { Button, DatePicker, Drawer, Form, FormProps, Input, Select, Space } from 'antd';
import dayjs from 'dayjs';

import Upload from '@/components/upload';

import { store } from '@/store';

import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import {
  safeEquipmentManagementAdd,
  safeEquipmentManagementUpdate
} from '@/services/bizApi/anquantezhongshebaoguanlibiaojiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const [managerData, setManagerData] = useState<BASE.OrgUserInfoVOduixiang[]>([]);

  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        safetyManager: values?.safetyManagerId
          ? managerData.find((item) => item.id === values?.safetyManagerId)?.fullName
          : undefined,
        nextInspectionDate: values?.nextInspectionDate
          ? dayjs(values?.nextInspectionDate).format('YYYY-MM-DD')
          : undefined,
        attachmentNextInspectionDate: values?.attachmentNextInspectionDate
          ? dayjs(values?.attachmentNextInspectionDate).format('YYYY-MM-DD')
          : undefined
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit'
        ? safeEquipmentManagementUpdate(query)
        : safeEquipmentManagementAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData,
              nextInspectionDate: arg.rowData?.nextInspectionDate
                ? dayjs(arg.rowData?.nextInspectionDate)
                : undefined,
              attachmentNextInspectionDate: arg.rowData?.attachmentNextInspectionDate
                ? dayjs(arg.rowData?.attachmentNextInspectionDate)
                : undefined
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增',
          edit: '编辑',
          detail: '详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="设备所在区域"
          name="area"
          rules={[
            {
              required: true,
              message: '请输入设备所在区域'
            }
          ]}
        >
          <Input placeholder="请输入设备所在区域" />
        </Form.Item>
        <Form.Item
          label="设备位置"
          name="location"
          rules={[
            {
              required: true,
              message: '请输入设备位置'
            }
          ]}
        >
          <Input placeholder="请输入设备位置" />
        </Form.Item>
        <Form.Item
          label="设备类型"
          name="equipmentType"
          rules={[
            {
              required: false,
              message: '请输入设备类型'
            }
          ]}
        >
          <Input placeholder="请输入设备类型" />
        </Form.Item>
        <Form.Item
          label="使用状态"
          name="usageStatus"
          rules={[
            {
              required: false,
              message: '请选择使用状态'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择使用状态"
            options={[
              {
                label: '使用中',
                value: 1
              },
              {
                label: '已报废',
                value: 2
              },
              {
                label: '闲置',
                value: 3
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="设备注册代码"
          name="registrationCode"
          rules={[
            {
              required: false,
              message: '请输入设备注册代码'
            }
          ]}
        >
          <Input placeholder="请输入设备注册代码" />
        </Form.Item>
        <Form.Item
          label="注册状态"
          name="registrationStatus"
          rules={[
            {
              required: false,
              message: '请选择注册状态'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择注册状态"
            options={[
              {
                label: '未注册',
                value: 2
              },
              {
                label: '已注册',
                value: 1
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="设备代码"
          name="equipmentCode"
          rules={[
            {
              required: false,
              message: '请输入设备代码'
            }
          ]}
        >
          <Input placeholder="请输入设备代码" />
        </Form.Item>
        <Form.Item
          label="设备下次检验日期"
          name="nextInspectionDate"
          rules={[
            {
              required: true,
              message: '请选择设备下次检验日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择设备下次检验日期" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="附件下次检验日期"
          name="attachmentNextInspectionDate"
          rules={[
            {
              required: true,
              message: '请选择附件下次检验日期'
            }
          ]}
        >
          <DatePicker placeholder="请选择附件下次检验日期" style={{ width: '100%' }} />
        </Form.Item>
        <Form.Item
          label="制造出厂代码"
          name="manufactureCode"
          rules={[
            {
              required: false,
              message: '请输入制造出厂代码'
            }
          ]}
        >
          <Input placeholder="请输入制造出厂代码" />
        </Form.Item>
        <Form.Item
          label="使用单位"
          name="usingOrganization"
          rules={[
            {
              required: false,
              message: '请输入使用单位'
            }
          ]}
        >
          <Input placeholder="请输入使用单位" />
        </Form.Item>
        <Form.Item
          label="维保单位"
          name="maintenanceOrganization"
          rules={[
            {
              required: false,
              message: '请输入维保单位'
            }
          ]}
        >
          <Input placeholder="请输入维保单位" />
        </Form.Item>
        {/* <Form.Item
          label="安管人员"
          name="safetyManager"
          rules={[
            {
              required: true,
              message: '请输入安管人员'
            }
          ]}
        >
          <Input placeholder="请输入安管人员" />
        </Form.Item> */}
        <ProFormSelect
          name="safetyManagerId"
          label="安管人员"
          placeholder="请选择安管人员"
          rules={[{ required: true, message: '请选择安管人员' }]}
          request={async () => {
            const res = await orgUserInfoVoPage({ page: 1, size: 1000 });
            setManagerData(res?.data?.records || []);
            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="安管人员电话"
          name="safetyManagerPhone"
          rules={[
            {
              required: false,
              message: '请输入安管人员电话'
            }
          ]}
        >
          <Input placeholder="请输入安管人员电话" />
        </Form.Item>
        <Form.Item
          label="附件"
          name="fileId"
          rules={[
            {
              required: false,
              message: '请上传附件'
            }
          ]}
        >
          <Upload
            // base64
            //  accept="image/*"
            maxCount={1}
          >
            <Button>上传</Button>
          </Upload>
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
